package code.producerandconsumer;

import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable {
    private final BlockingQueue<Integer> queue;

    public Consumer(BlockingQueue<Integer> queue) {
        this.queue = queue;
    }


    @Override
    public void run() {
        try {
            while (true) {
                consume();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void consume() throws InterruptedException {
        synchronized (queue) {
            while (queue.isEmpty()) {
                System.out.println("缓冲区为空，消费者等待...");
                queue.wait();
            }
            Integer i = queue.take();
            System.out.println("消费者消费物品：" + i);
            queue.notifyAll();  // 唤醒所有等待的生产者线程
        }
    }
}
